﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using DECOR.BL.BE;
using DECOR.BL.BC;
using System.Collections.Generic;
using AjaxControlToolkit;
namespace DECOR.WebApp
{
    public partial class BuscaPart : System.Web.UI.Page
    {
        //private ClienteBE _lvObjCliente;
        private decimal _subTotalML = 0m;
        private decimal _totalML = 0m;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                List<GenericBE> lstOrgVtas = ClienteBC.Instance.listaOrgVtas("");
                cmbSociedad.DataValueField = "Codigo";
                cmbSociedad.DataTextField = "Descripcion";
                cmbSociedad.DataSource = lstOrgVtas;
                cmbSociedad.DataBind();
            }
        }

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] buscaClientes(string prefixText, int count)
        {
            string[] retVal;
            List<ClienteBE> lstClientes = ClienteBC.Instance.buscar(prefixText);
            List<string> lst = new List<string>();
            int total = lstClientes.Count < count ? lstClientes.Count : count;
            for (int i = 0; i < total; i++)
            {
                string item = AjaxControlToolkit.AutoCompleteExtender.CreateAutoCompleteItem(lstClientes[i].Descripcion, lstClientes[i].Codigo);
                lst.Add(item);
            }
            retVal = lst.ToArray();
            return retVal;
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                string codCliente = txtCodCuentaDeudor.Text.Trim();
                string fecha = txtFechaAbiertas.Text.Trim(); DateTime pFecha = DateTime.Today;
                if (!string.IsNullOrEmpty(codCliente) && !string.IsNullOrEmpty(cmbSociedad.SelectedValue))
                {
                    if (!string.IsNullOrEmpty(fecha))
                    {
                        try
                        {
                            pFecha = Convert.ToDateTime(fecha);
                        }
                        catch (Exception ex) { Session["Mensaje"] = "Fecha ingresada es inválida.\n" + ex.Message; }
                    }
                    List<PartidaBE> lstPartidas = PartidaBC.Instance.buscaPartAbiertas(codCliente, cmbSociedad.SelectedValue, pFecha);

                    var xys = from x in lstPartidas
                              orderby x.ClaseDoc, x.NumDocumento, x.CodReferencia
                              group x by new { x.ClaseDoc };

                    List<PartidaGrpBE> lstPartidasGrp = new List<PartidaGrpBE>();
                    foreach (var xy in xys)
                    {
                        PartidaGrpBE objPartidasGrp = new PartidaGrpBE();

                        objPartidasGrp.ClaseDoc = xy.Key.ClaseDoc;
                        objPartidasGrp.ImporteTotalML = xy.Sum(item => item.ImporteMonLocal);

                        lstPartidasGrp.Add(objPartidasGrp);
                    }

                    //decimal impTotal = 0m;
                    foreach (PartidaGrpBE item in lstPartidasGrp)
                    {
                        item.Partidas = lstPartidas.FindAll(X => X.ClaseDoc == item.ClaseDoc);
                    }

                    dlDetalle.DataSource = lstPartidasGrp;
                    dlDetalle.DataBind();
                }
            }
            catch (Exception ex)
            {
                Session["Mensaje"] = ex.Message;
            }
            finally
            {
                ((Site)Master).muestraMensajes();
            }
        }

        protected void dgPartidas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                this._subTotalML += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ImporteMonLocal"));
            }
            else if (e.Row.RowType == DataControlRowType.Footer)
            {
                e.Row.Cells[5].Text = string.Format("{0:n}", this._subTotalML);
                e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Right;
                e.Row.Cells[5].VerticalAlign = VerticalAlign.Top;
                e.Row.VerticalAlign = VerticalAlign.Top;

                this._totalML += this._subTotalML;
                this._subTotalML = 0m;
            }
        }

        protected void dlDetalle_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Footer)
            {
                Label lblImporteTotal = (Label)e.Item.FindControl("lblImporteTotal");
                lblImporteTotal.Text = string.Format("{0:0,0.00}", this._totalML);
            }
        }
    }
}
